package com.example.shixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.shixun.dao.AdminDao;
import com.example.shixun.pojo.Admin;
import com.example.shixun.pojo.AdminDTO;
import com.example.shixun.pojo.Result;
import com.example.shixun.service.AdminService;
import com.example.shixun.utils.JwtUtils;
import com.example.shixun.utils.Md5;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 管理员表(Admin)表服务实现类
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminDao adminDao;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    Md5 md5=new Md5();
    @Override
    public Result login(Admin admin) {
        System.out.println("AdminServiceLogin msg=:"+admin.toString());
        admin.setPassword(md5.code(admin.getPassword()));
        Admin radmin=adminDao.login(admin);
        if(radmin==null) return Result.fail("登录失败，请检查账户密码");
        String jwtToken = JwtUtils.getJwtToken(radmin.getId().toString(), radmin.getName(),"admin");
        AdminDTO adminDTO=new AdminDTO();
        BeanUtils.copyProperties(radmin, adminDTO);
        // 加入到redis中
        System.out.println(jwtToken);
        System.out.println(adminDTO.toString());
        System.out.println(radmin.toString());
        stringRedisTemplate.opsForValue().set(jwtToken, JSON.toJSONString(adminDTO), 1, TimeUnit.DAYS);
        return Result.success("登录成功",jwtToken);
    }

    @Override
    public AdminDTO getAdminTokenInfo(String token) {
        String adminJson=stringRedisTemplate.opsForValue().get(token);
        System.out.println("adminJson="+adminJson);
        return JSON.parseObject(adminJson, AdminDTO.class);
    }

    @Override
    public Result getAdminById(Integer id) {
        if(id==null) return Result.fail("id==null");
        Admin admin = adminDao.findById(id);
        if(admin==null) return Result.fail("请检查账号密码");
        return Result.success(admin);
    }
}
